<script lang="ts" setup>
import { MoreOutlined } from '@vicons/antd'
import type { DropdownOption } from 'naive-ui'
import TabItemComp from './tab-item.vue'
import type { TabItem } from '@/layouts/multi-tab/type.ts'

const router = useRouter()

const { tabList, current, closeTab, refresh } = useMultiTab()

const contextParam = reactive({
  x: 0,
  y: 0,
  show: false,
})

function handleClose(path: string) {
  closeTab(path)
}

function handleContextMenu(e: MouseEvent) {
  e.preventDefault()
  contextParam.show = false
  nextTick().then(() => {
    contextParam.show = true
    contextParam.x = e.clientX
    contextParam.y = e.clientY
  })
}

function renderTab(item: TabItem) {
  return h(TabItemComp, { item, onContextMenu: handleContextMenu })
}

const actionOpt = computed<DropdownOption[]>(() => [
  {
    label: '关闭当前页',
    key: 'closeCurrent',
    disabled: tabList.value.length <= 1,
  },
  { label: '刷新当前页', key: 'refreshCurrent' },
])

function handleActionSelect(key: string) {
  if (key === 'closeCurrent')
    closeTab()
  else if (key === 'refreshCurrent')
    refresh()

  contextParam.show = false
}

function handleChange(val: string) {
  router.push(val)
  contextParam.show = false
}
</script>

<template>
  <n-tabs
    :value="current"
    class="pt-6px bg-white dark:bg-transparent"
    tab-style="min-width: 80px;"
    type="card"
    @close="handleClose"
    @update:value="handleChange"
  >
    <!-- 前置插槽  -->
    <template #prefix>
      <div class="ml-12px" />
    </template>
    <!-- 后置插槽 -->
    <template #suffix>
      <div class="mr-12px">
        <n-dropdown
          :options="actionOpt"
          trigger="click"
          @select="handleActionSelect"
        >
          <n-icon class="cursor-pointer" size="16">
            <MoreOutlined />
          </n-icon>
        </n-dropdown>
      </div>
    </template>
    <n-tab-pane
      v-for="panel in tabList"
      :key="panel.path"
      :name="panel.path"
      :tab="renderTab(panel)"
      closable
    />
  </n-tabs>
  <n-dropdown
    :options="actionOpt"
    :show="contextParam.show"
    :x="contextParam.x"
    :y="contextParam.y"
    placement="bottom-start"
    trigger="manual"
    @clickoutside="contextParam.show = false"
    @select="handleActionSelect"
  />
</template>
